package com.cy.jwt.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    /**
     * 秘钥
     */
    private static String secret="AAABBBCCCDDDEEE";
    /**
     * 有效期，单位秒
     * 默认30分钟
     */
    private static Long expirationTimeInSecond=1800L;

    /**
     * 从token中获取claim
     *
     * @param token token
     * @return claim
     */
    public static Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new IllegalArgumentException("Token invalided.");
        }
    }

    /**
     * 判断token是否过期
     * @param token token
     * @return 已过期返回true，未过期返回false
     */
    public static Boolean isTokenExpired(String token) {
        Date expiration = getClaimsFromToken(token).getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 为指定用户生成token
     * @param claims 用户信息
     * @return token
     */
    public static String generateToken(Map<String, Object> claims) {
        Date createdTime = new Date();
        System.out.println("createdTime"+createdTime);
        Date expirationTime = new Date(System.currentTimeMillis() + expirationTimeInSecond * 1000);
        System.out.println("expirationTime"+expirationTime);
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(createdTime)
                .setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
    }
}

